package pl.wroc.uni.ii.evolution.distribution.workers.applet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class EvReaderThread extends Thread {
  private PipedInputStream pi;
  private JTextArea text_area;
  private BufferedReader reader;
  
  public EvReaderThread(PipedInputStream pi, JTextArea text_area) {
    this.pi = pi;
    this.text_area = text_area;
    this.reader = new BufferedReader( new InputStreamReader( pi ) );
  }

  public void run() {
    try {
      while (true) {
        try {
          String tmp = reader.readLine(); 

          if (tmp != null) {
            SwingUtilities.invokeLater(new Appender(tmp, text_area));
          } else {
            sleep(100);
          }

        } catch (IOException ex) {} 
      }
    } catch (InterruptedException ex) {

    }
  }
}
class Appender implements Runnable {
  private String tmp;
  private JTextArea  text_area;

  public Appender(String tmp, JTextArea text_area) {
     this.tmp = tmp;
     this.text_area = text_area;
  }

  public void run() {
    text_area.append(tmp);
    text_area.append("\n");
    text_area.setCaretPosition(text_area.getDocument().getLength());
  }
}
